<!--
 * @Author: your name
 * @Date: 2021-02-28 20:07:38
 * @LastEditTime: 2021-04-28 13:01:51
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jianfa-admin\src\page\common\components\addFiles.vue
-->
<template>
  <el-dialog
    :title="`拖拽排序`"
    :visible="visible"
    v-dialogdrag
    @close="$emit('update:visible', false)"
    width="80%"
    top="10vh"
  >
    <div class="menu-list">
      <draggable v-model="myMenu" @start="onStart" @end="onEnd">
        <transition-group>
          <div class="menu-item" v-for="item in myMenu" :key="item.id">
            {{ item.class_name }}
          </div>
        </transition-group>
      </draggable>
    </div>
  </el-dialog>
</template>
<script>
import draggable from "vuedraggable";
export default {
  components: {
    draggable
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    currentMenu: {
      type: Object,
      default: {}
    },
    menu: {
      type: Array,
      default: []
    }
  },

  data() {
    return {
      myMenu: []
    };
  },
  watch: {
    menu: {
      handler() {
        this.myMenu = this.menu;
      }
    }
  },
  methods: {
    async Menusort(id, sort, table_name) {
      const { code } = await this.$api.menu.updateMenu({
        id,
        sort,
        table_name
      });
      if (!code) {
        this.$message.success("修改成功");
        this.$emit("getMenu");
      }
    }, //开始拖拽事件
    onStart(events) {
      console.log("events :>> ", events);
    },
    //拖拽结束事件
    onEnd({ newIndex, oldIndex }) {
      console.log("param :>> ", newIndex, oldIndex);
      console.log("this.myMenu :>> ", this.myMenu);
      const prev = this.myMenu[newIndex - 1]; //前一个
      const later = this.myMenu[newIndex + 1];
      let newSort = "";
      if (prev && later) {
        newSort = (+prev.sort + +later.sort) / 2;
      } else if (prev) {
        newSort = +prev.sort - 1;
      } else {
        newSort = +later.sort + 1;
      }
      this.Menusort(
        this.myMenu[newIndex].id,
        newSort,
        this.$route.meta.table_name
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.menu-list {
  height: 500px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  // justify-content: center;
  margin-top: -10px;
  padding: 30px 0;
  .menu-item {
    padding: 0 20rpx;
    text-align: center;
    font-size: 13px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 700px;
    height: 35px;
    border-radius: 10px;
    border: 1px solid #ccc;
    margin-top: 10px;
  }
}
</style>
